/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package nvPlaces;

import java.util.Enumeration;
import java.util.Hashtable;
import nvOrganism.nvOrganismMgr;
import org.nViron.nvCommon.nvStateMgr;
import org.nViron.nvData.nvDataEntity;
import org.nViron.nvRender.nvRenderer;
import org.nViron.nvSim.nvSimulator;

/**
 *
 * @author Roland
 */
public class nvPlacesMgr extends nvOrganismMgr {

    private Hashtable places = new Hashtable();
    private Hashtable enitityLookupTable = new Hashtable();
    private nvClusterer clusterer = new nvBasicClusterer();

    public nvPlacesMgr(nvSimulator simulator) {
        super(simulator);
    }

    @Override
    public void render(nvRenderer renderer) {
        for (Enumeration e = places.keys(); e.hasMoreElements();)
        {
            nvPlace place = (nvPlace)places.get(e.nextElement());
            place.render(renderer);
        }
    }

    @Override
    public void update() {
        // update places
        for (Enumeration e = places.keys(); e.hasMoreElements();)
        {
            Object key = e.nextElement();
            nvPlace place = (nvPlace)places.get(key);
            if (place.getStateMgr().getState() == nvStateMgr.DEAD) {
                places.remove(key);
            } else {
                place.update();
            }
        }
        clusterer.balancePlaces(places);
    }

    public void addPlace(nvPlace place) {
        places.put(place.getId(), place);
    }

    public nvPlace createPlace(nvDataEntity entity) {
        nvPlace place = new nvPlace(this, entity, clusterer);
        return place;
    }

    public nvClusterer getClusterer() {
        return clusterer;
    }

    public Hashtable getPlaces() {
        return places;
    }

    public nvPlace lookupPlaceByEntityId(nvDataEntity entity) {
        return (nvPlace)enitityLookupTable.get(entity.getId());
    }

    public nvPlace findPlaceForEntity(nvDataEntity entity) {
        return clusterer.findPlaceForEntity(places, entity);
    }

    public void removePlace(nvPlace place) {
        place.getStateMgr().setState(nvStateMgr.DEGENERATING);
    }

    public void addEntitiyToPlace(nvDataEntity entity, nvPlace place) {
        place.addEntity(entity, clusterer);
        enitityLookupTable.put(entity.getId(), place);
    }
}
